// 定义用户相关的仓库
import { defineStore } from "pinia";
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/setting";
// 引入获取验证码的请求方法
import { reqCode, reqUserLogin } from "@/api/hospital";
import type { LoginData, UserLoginResponseData } from "@/api/hospital/type";
// @ts-ignore
import { ElMessage } from "element-plus";
const useUserStore = defineStore('User', {
    state: (): any => {
        return {
            // 用于控制登陆组件的dialog显示与隐藏
            dialogVisible: false,
            userInfo: JSON.parse(GET_TOKEN() as string) || {}
        }
    },
    actions: {
        async getCode(phone: string) {
            let { code, data, message }: any = await reqCode(phone)
            if (code && data != null) {
                ElMessage({
                    type: 'success',
                    message: `验证码为: ${data} `,
                    duration: 4000
                });
                return data
            } else {
                ElMessage({
                    type: 'error',
                    message: `验证码获取失败 请稍后再试`,
                })
                return Promise.reject(new Error(message))
            }
        },
        async userLogin(loginParam: LoginData) {
            let { code, data, message }: UserLoginResponseData = await reqUserLogin(loginParam);
            if (code === 200) {
                this.userInfo = data;

                // 本地存储持久化用户信息
                SET_TOKEN(JSON.stringify(this.userInfo))
                ElMessage({
                    type: 'success',
                    message: `登陆成功`,
                })
                return 'ok'
            } else {
                ElMessage({
                    type: 'error',
                    message: `登陆失败`,
                })
                return Promise.reject(new Error(message))
            }
        },
        // 退出登陆
        logOut() {
            this.userInfo = {
                name: '',
                token: ''
            };
            REMOVE_TOKEN();
            ElMessage({
                type: 'warning',
                message: '您已退出登陆'
            })
        },
        // 查询微信扫码的接口
        queryState() {
            let timer = setInterval(() => {
                if (GET_TOKEN()) {
                    this.dialogVisible = false
                    this.userInfo = JSON.parse(GET_TOKEN() as string)
                    clearInterval(timer)
                }
            }, 250)
        }
    },
    getters: {},
})

export default useUserStore